<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>登录</title>
    <link rel="stylesheet" href="css/common.css">
    <link rel="stylesheet" href="css/login.css">
</head>
<body>
<div class="nav">
    五子棋对战
</div>
<div class="login-container">
    <!-- 登录界面对话框 -->
    <div class="login-dialog">
        <h3>登录</h3>
        <div class="row">
            <span>用户名</span>
            <input type="text" id="username">
        </div>
        <div class="row">
            <span>密码</span>
            <input type="password" id="password">
        </div>
        <div class="row">
            <button id="submit">提交</button>
        </div>
        <!-- 添加注册链接 -->
        <div class="row">
            <span>没有账号？</span>
            <a href="register.html">点击注册</a>
        </div>
    </div>
</div>

<script src="./js/jquery.min.js"></script>
<script>
    let usernameInput = document.querySelector('#username');
    let passwordInput = document.querySelector('#password');
    let submitButton = document.querySelector('#submit');
    submitButton.onclick = function() {
        // 检查用户名和密码是否为空
        if (usernameInput.value.trim() === '') {
            alert("请输入账号!");
            return;
        }
        if (passwordInput.value.trim() === '') {
            alert("密码不能为空!");
            return;
        }

        // 禁用提交按钮，避免重复提交
        submitButton.disabled = true;

        $.ajax({
            type: 'post',
            url: '/login',
            data: {
                username: usernameInput.value,
                password: passwordInput.value,
            },
            success: function(response) {
                if (response.userId > 0) {
                    alert("登录成功!");
                    location.assign('/game_hall.html');
                } else {
                    if (response.message) {
                        alert(response.message);
                    } else {
                        alert("登录失败!");
                    }
                    usernameInput.value = '';
                    passwordInput.value = '';
                }
            },
            error: function(xhr) {
                if (xhr.responseJSON && xhr.responseJSON.message) {
                    alert(xhr.responseJSON.message);
                } else {
                    alert("登录失败!");
                }
                usernameInput.value = '';
                passwordInput.value = '';
            },
            complete: function() {
                submitButton.disabled = false;
            }
        });
    }
</script>
</body>
</html>
